package com.icesoft.core.common.util;

import java.io.IOException;
import java.text.SimpleDateFormat;

import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public abstract class JsonUtil {
	protected static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
	private static final ObjectMapper mapper = new ObjectMapper();
	private static final ObjectMapper mapperNonNull = new ObjectMapper();
	static {
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
		mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		mapperNonNull.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	}

	public static String toJson(Object obj) {
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			log.error("object to Json 转换错误，obj = " + obj, e);
		}
		return null;
	}

	public static String toJsonNonNull(Object obj) {
		try {

			return mapperNonNull.writeValueAsString(obj);
		} catch (JsonProcessingException var2) {
			log.error("toJsonNonNull object to Json 转换错误，obj = " + obj, var2);
			return null;
		}
	}

	public static <T> T toObject(String json, Class<T> cls) {
		try {
			return mapper.readValue(json, cls);
		} catch (IOException e) {
			log.error("json to Object 转换错误，json = " + json, e);
		}
		return null;
	}

	public static <T> T toObject(String json, TypeReference<T> cls) {
		try {
			return mapper.readValue(json, cls);
		} catch (IOException e) {
			log.error("json to TypeReference Object 转换错误，json = " + json, e);
		}
		return null;
	}
}
